<!--# 
var name = name!"attachement";
var tip = tip!"attachement";
var readonly = readonly!"false";
var uploadURL = ctxPath+"/core/file/uploadAttachment.json";
var chooseId = name+"List";
var uploadId = name+"ListAction";
var filesListId = name+"DataList";
//加载已经在数据库列表
var files = (isNew=="true")?[]:core.file(batchFileUUID);

-->
<div class="layui-upload">
		<input type="hidden" name="${name}" value="${batchFileUUID}" ${isNotEmpty(layVerify)?('lay-verify="'+layVerify+'"'):''} />
		<!--# if(readonly=="false"){  -->
		<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" style="margin-top: 5px;"
			id="${chooseId}">选择文件</button>

		<!--<button type="button" class="layui-btn" id="${uploadId}">开始上传</button>-->
		<!--# } -->
	</br>
    <div class="layui-upload-list" style="margin:0px 0px 40px 0px;">
		<table class="layui-table" style="width: 660px;clear:both;margin:0px;">
			<thead>
				<tr>
					<th style="width: 300px;padding:4px 15px;">文件名</th>
					<th style="width: 150px;padding:4px 15px;">状态</th>
					<th style="width: 210px;padding:4px 15px;">操作</th>
				</tr>
			</thead>
			<tbody id="${filesListId}">
				<!--# for(file in files){
				  -->
		      	<tr>
		      	<td file-id="${file.id}">${file.name}</td>
		        <td><span style="color: #5FB878;">上传成功</span></td>
		        <td>
					<!--# if(readonly=="false"){  -->

					<button class="layui-btn layui-btn-mini  layui-btn-danger demo-delete layui-btn-sm">删除</button>
					<!--# } -->

			        <button class="layui-btn layui-btn-mini  demo-preview layui-btn-sm">预览</button>
			        <button class="layui-btn layui-btn-mini  demo-download layui-btn-sm">下载</button>
		        </td>
		      </tr>
      			<!--# }  -->
			</tbody>
		</table>
	</div>

</div>
<script>
var previewStr = '<button class="layui-btn layui-btn-mini demo-preview layui-btn-sm">预览</button>';
var deleteStr = '<button class="layui-btn layui-btn-mini  demo-delete layui-btn-danger layui-btn-sm">删除</button>';
var downloadStr ='<button class="layui-btn layui-btn-mini demo-download layui-btn-sm">下载</button>';
layui.use('upload',
function() {
    var $ = layui.jquery,
    upload = layui.upload;
    var demoListView = $('#${filesListId}'),
    uploadListIns = upload.render({
        elem: '#${chooseId}',
        url: '${uploadURL}',
        accept: 'file', //指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
        exts: 'pdf|jpg|png|gif', //只允许上传指定后缀文件
        multiple: false,
        number:1,
        auto: true,
		size: 20480, //最大允许上传的文件大小,单位kb
        data: {
            "batchFileUUID": "${batchFileUUID}",
            "bizId":"${bizId!}",
            "bizType":"${bizType}"
        },
        // bindAction: '#${uploadId}',
        choose: function(obj) {
            console.log("choose");
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function(index, file, result) {
                var tr = $(['<tr id="${name}Upload-' + index + '">', '<td></td>', '<td>' + file.name + '</td>', '<td>等待上传</td>', '<td>', '<button class="layui-btn layui-btn-mini demo-reload  layui-hide">重传</button>', '<button class="layui-btn layui-btn-mini layui-btn-danger demo-cancel">取消</button>', '</td>', '</tr>'].join(''));
                //单个重传
                tr.find('.demo-reload').on('click',
                function() {
                    obj.upload(index, file);
                });

                //取消
                tr.find('.demo-cancel').on('click',
                function() {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                demoListView.append(tr);
            });
        },
        done: function(res, index, upload) {
            // console.log("done")
            // console.log(res);
            // console.log(index);
            // console.log(upload);
            var tr = $(['<tr id="${name}Upload-' + index + '">', '<td>' + '' + '</td>', '<td>等待上传</td>', '<td>', '<button class="layui-btn layui-btn-mini demo-reload  layui-hide ">重传</button>', '<button class="layui-btn layui-btn-mini layui-btn-danger demo-cancel">取消</button>', '</td>', '</tr>'].join(''));
            demoListView.append(tr);

            if (res.code != 0) {
                this.error(index, upload);
                return
            } //上传成功
            var tr = demoListView.find('tr#${name}Upload-' + index),
            tds = tr.children();
            tds.eq(0).attr("file-id", res.data.id);
            tds.eq(0).html(  res.data.name);
            tds.eq(1).html('<span style="color: #5FB878;">上传成功</span>');
            tds.eq(2).html(deleteStr+previewStr +downloadStr); //清空操作
            initTr(tr);
            // return delete this.files[index]; //删除文件队列已经上传成功的文件
        },
        error: function(index, upload) {
            var tr = demoListView.find('tr#${name}upload-' + index),
            tds = tr.children();
            tds.eq(1).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(2).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    var trs = demoListView.children();
    for (var i = 0; i < trs.length; i++) {
        initTr($(trs[i]));
    }

    function initTr(tr) {
    		var tds = tr.children();
    		var fileId = tds.eq(0).attr("file-id");
    		var fileName= tds.eq(0).html();
        tr.find('.demo-delete').on('click',function() {
            
            Common.post("/core/file/deleteAttachment.json", {
                "fileId": fileId,
                "batchFileUUID": "${batchFileUUID}"
            },
            function() {
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                Common.info("删除成功");
            });
            return false;

        });
        //预览服务器文件
        tr.find('.demo-preview').on('click',
        function() {
            //文件下载地址
            console.log(this);
            var parentNode = this.parentNode;
            console.log(parentNode);

            var file = encodeURIComponent("http://" + window.location.host+"/core/file/download/"+fileId+"/${batchFileUUID}/"+fileName);
            var fileURL =  "${ctxPath}/core/file/download/"+fileId+"/${batchFileUUID}/"+fileName;
            //8012为预览服务器地址，参考 https://gitee.com/kekingcn/file-online-preview 安装
            // Common.openDlg= ("/plugins/pdfjs/web/viewer.html?file=/core/file/download/"+fileId+"/${batchFileUUID}/"+fileName,"标题");
            // location.href= "/plugins/pdfjs/web/viewer.html?file=/core/file/download/"+fileId+"/${batchFileUUID}/"+fileName;
            var endWith = Common.endWith(fileName);
            var widhtSize = $(window).width(); //浏览器当前可视区域宽度
            var heightSize = $(window).height(); //浏览器当前可视区域高度
			if(endWith){
            	// Lib.innerAddTab("/plugins/pdfjs/web/viewer.html?file="+fileURL,"undefined",fileName);
                //Common.openDlg("/plugins/pdfjs/web/viewer.html?file="+fileURL,fileName);

                var index = layer.open({
                    type: 2, //type-2 ifram弹出框 动态加载页面
                    fix: false,
                    shade: false,
                    title: '文件预览', //不显示标题
                    offset: 'rb',
                    area: [widhtSize/2-100+'px', heightSize-30+'px'],
                    moveType: 1, //拖拽模式，0或者1
                    btn: ['关闭','全屏','退出全屏'],
                    btnAlign: 'c',
                    content:"${ctxPath}/plugins/pdfjs/web/viewer.html?file="+fileURL,
                    cancel: function () {
                        //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
                    },yes: function(index, layero){
                        layer.closeAll();
                    },btn2: function(index, layero){
                        //按钮【按钮二】的回调
                        layer.full(index);
                        return false;//开启该代码可禁止点击该按钮关闭
                    },btn3: function(index, layero){
                        //按钮【按钮三】的回调
                        layer.restore(index);
                        return false;//开启该代码可禁止点击该按钮关闭
                    }
                });
			}else{
                // Lib.innerAddTab("/plugins/pdfjs/web/imghtml.html?imgFile="+fileURL,"undefined",fileName);
				//Common.openDlg("/plugins/pdfjs/web/imghtml.html?imgFile="+fileURL,fileName);

                var imgHtml = "<div style='margin: 10px;'><img src='" + fileURL + "' /></div>";
                //捕获页
                var index = layer.open({
                    type: 1,  //普通文本弹出框
                    fix: false,
                    shade: false,
                    offset: 'rb',
                    title: '文件预览', //不显示标题
                    area: [widhtSize/2-100+'px', heightSize-30+'px'], //弹出框大小
                    moveType: 1, //拖拽模式，0或者1
                    btn: ['关闭','全屏','退出全屏'],
                    btnAlign: 'c',
                    content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    cancel: function () {
                        //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
                    },yes: function(index, layero){
                        layer.closeAll();
                    },btn2: function(index, layero){
                    	//按钮【按钮二】的回调
                        layer.full(index);
                    	return false;//开启该代码可禁止点击该按钮关闭
                	},btn3: function(index, layero){
                        //按钮【按钮三】的回调
                        layer.restore(index);
                        return false;//开启该代码可禁止点击该按钮关闭
                    }
                });
            }
           	return false;
        });
        
        //下载服务器文件
        tr.find('.demo-download').on('click',
        function() {
            //文件下载地址
            var address = "${ctxPath}/core/file/download/"+fileId+"/${batchFileUUID}/"+fileName;
            console.log(address);
           	window.location.href=address;
           	return false;
        });
    }

});
 </script>

